package com.tanhua.server.responseadvice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.common.utils.Cache;
import com.tanhua.server.interceptor.RedisCacheInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.concurrent.TimeUnit;

@ControllerAdvice
@Slf4j
public class MyResponseBodyAdvice implements ResponseBodyAdvice {
    @Value("${tanhua.cache.enable}")
    private boolean enable;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    private static final ObjectMapper MAPPER=new ObjectMapper();
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        // 开关处于开启状态  是get请求  包含了@Cache注解

        return enable&&methodParameter.hasMethodAnnotation(Cache.class)
                &&methodParameter.hasMethodAnnotation(GetMapping.class);
    }

    @Override
   public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if(null==body){
            return null;
        }

            String redisValue=null;
        try {
            if(body instanceof String){
                redisValue=(String)body;
            }else {
                redisValue=MAPPER.writeValueAsString(body);
            }
            System.out.println("我缓存数据了");
        String redisKey= RedisCacheInterceptor.createRedisKey(((ServletServerHttpRequest)serverHttpRequest).getServletRequest());
            Cache cache = methodParameter.getMethodAnnotation(Cache.class);
            this.redisTemplate.opsForValue().set(redisKey,redisValue,Long.valueOf(cache.time()), TimeUnit.SECONDS);

    } catch (Exception e) {
        log.error("解析字符串错误",e);
    }
        return body;
    }
}
